<?php
/**
 * File Upload Component 
 * Component for easy file upload management
 *  
 * @package    Lazy Framework
 * @subpackage component
 * @author     Eduardo Marcolino <eduardo.marcolino@gmail.com>
 * @copyright  (c) 2010 Eduardo Marcolino <eduardo.marcolino@gmail.com>
 */

class UploadedFile {
    
    private $file;
    private $unique_name;

    public function __construct($file_request) {
        $this->file = $file_request;
        $this->generateUniqueName();
    }

    public function getErrorCode(){
        return $this->file['error'];
    }

    public function isEmpty() {
        return $this->getErrorCode() == 4 ? true : false;
    }
    public function getErrorMessage() {
        switch ($this->getErrorCode()) {
            case UPLOAD_ERR_INI_SIZE:
                return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            case UPLOAD_ERR_FORM_SIZE:
                return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            case UPLOAD_ERR_PARTIAL:
                return 'The uploaded file was only partially uploaded';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded';
            case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing a temporary folder';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk';
            case UPLOAD_ERR_EXTENSION:
                return 'File upload stopped by extension';
            default:
                return 'Unknown upload error';
        }
    } 

    public function getOriginalName() {
        return $this->file['name'];
    }

    public function getUniqueName() {
        return $this->unique_name;
    }

    private function generateUniqueName(){
        $ext = end(explode(".", $this->getOriginalName()));
        $this->unique_name = md5(microtime(true)).'.'.$ext;
    }
    
    private function save($filename,$dir){
        return move_uploaded_file($this->file["tmp_name"], $dir.$filename);
    }
    public function saveWithOriginalName($dir){
        return $this->save($this->getOriginalName(),$dir);
    }
    public function saveWithUniqueName($dir){
        return $this->save($this->getUniqueName(),$dir);
    }

    public function getType(){
        return $this->file['type'];
    }

    public function getSize(){
        return $this->file['size'];
    }
}

?>
